package cn.kailangtu.myapplication.services;


import android.annotation.SuppressLint;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Handler;
import android.os.IBinder;
import android.os.Looper;
import android.os.SystemClock;
import android.util.Log;

import androidx.core.app.NotificationCompat;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.Arrays;
import java.util.Random;
import java.util.concurrent.LinkedBlockingQueue;

import cn.kailangtu.myapplication.events.SerialData;
import cn.kailangtu.myapplication.events.SerialDataRS481;
import cn.kailangtu.serialport.CommonUtils;
import cn.kailangtu.serialport.ModbusError;
import cn.kailangtu.serialport.ModbusRtuMaster;
import cn.kailangtu.serialport.ModbusSlave;
import cn.kailangtu.serialport.ReceiveData;
import cn.kailangtu.serialport.ReceiveMsgListener;
import cn.kailangtu.serialport.SerialPortApi485;
import cn.kailangtu.serialportv2.DataVersion2;
import cn.kailangtu.serialportv2.ReceiveMsgListenerV2;

public class Service_Rs485_1 extends Service {
    byte[]data1;
    byte[]data2;
    int time1;

    SerialPortApi485 serialPortApi =new SerialPortApi485();

    public Service_Rs485_1() {
    }

    @Override
    public void onCreate() {
        super.onCreate();
         EventBus.getDefault().register(this);
            init();

          testSpeed();
           testSpeed1();

    }

    @Override
    public void onDestroy() {
        //EventBus.getDefault().unregister(this);
    }

    @Override
    public IBinder onBind(Intent intent) {
        // TODO: Return the communication channel to the service.
        throw new UnsupportedOperationException("Not yet implemented");
    }


    @SuppressLint("ForegroundServiceType")
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {


        //启动服务用
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationChannel channel = new NotificationChannel("persident", "persident",
                    NotificationManager.IMPORTANCE_LOW);
            NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
            manager.createNotificationChannel(channel);
            Notification notification = new NotificationCompat.Builder(this, "persident")
                    .setAutoCancel(true)
                    .setCategory(Notification.CATEGORY_SERVICE)
                    .setOngoing(true)
                    .setPriority(NotificationManager.IMPORTANCE_LOW).build();
            startForeground(12, notification);
        }

        return super.onStartCommand(intent, flags, startId);
    }

    private void init() {

        if(serialPortApi.openSerialPort("/dev/ttyHSL2", 9600, 0)){
            Log.d("rrrrrrrr","打开串口成功：");

        } else {
            Log.d("rrrrrrrr","打开串口失败：");

        }
    }


    public void testSpeed()
    {

        ModbusRtuMaster modbusRtuMaster = new ModbusRtuMaster();
        serialPortApi.shouBytes(new ReceiveMsgListenerV2() {
            @Override
            public void errorMsg(String msg) {
            }
            @Override
            public void onReceiveData(byte[] data) {
               // Log.d("rrrrrrrr", "onReceiveData");
                data1 = modbusRtuMaster.hufu(data);
               // Log.d("RRRRRRRRRRR",CommonUtils.ByteArrayToHexString(data1));
            }
        });

        new Thread(new Runnable() {
            @Override
            public void run() {
                Random r = new Random();
                while(true) {

                    data1 = null;
                    try {
                        String aaa = "01020000001079C6";
                        serialPortApi.sendBytes(CommonUtils.hexStringToByteArray(aaa));
                        //serialPortApi.sendBytes(CommonUtils.hexStringToByteArray(modbusRtuMaster.readCoils(1, 2, 16)));
                    } catch (Exception e) {
                    }


                    while (true) {
                        if (data1 == null) {
                            time1 = time1 + 1;
                        }
                        if(time1>100){
                            Log.d("rrrrrrrr", "通信中断");
                            break;}
                        if(data1!=null){
                            data2=data1;
                            break;}
                        SystemClock.sleep(10);
                    }
                    if(data1!=null){
                  //  Log.d("rrrrrrrr", "ooo"+data1[0]);
                        SystemClock.sleep(5);
                    }
                    time1=0;


                }
            }
        }).start();
    }
byte[] data3=new byte[4];
    public void testSpeed1()
    {
        new Thread(new Runnable() {
            @Override
            public void run() {
                while(true) {
                  //  Log.d("rrrrrrrr", "kkk");
                    if(data2!=null && data2.length > 4){
                          //  Log.d("rrrrrrrr", "kkk" + data2.length);
                        System.arraycopy(data2, data2.length-4, data3, 0, 2);
                        EventBus.getDefault().post(new SerialDataRS481(data3));
                    }
                   //
                    SystemClock.sleep(500);
                }
            }
        }).start();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(SerialData event){
        // binding.textviewFirst.setText(event.toString());
       // data=event.getA1();
       // Log.e("rrrrrrrr","uuuu"+data[0]);
    }
    public void onMessageEvent(SerialDataRS481 event){
        // binding.textviewFirst.setText(event.toString());
        // data=event.getA1();
        // Log.e("rrrrrrrr","uuuu"+data[0]);
    }



}

